#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/9/1 19:34
# @Author  : 1823218990@qq.com
# @File    : main_recorded
# @Software: Pycharm
"""
"""
import sys
import os
import subprocess
from datetime import datetime
from multiprocessing import Process, freeze_support
from threading import Thread
from tkinter import Tk
import tkinter as tk
CODE_ERROR = -1
real_cfile = os.path.abspath(__file__)
real_path = os.path.dirname(real_cfile)
if sys.platform.startswith("win"):
    ffmpeg_bin = os.path.join(real_path, "ffmpeg\\bin\\ffmpeg.exe")
    ffprobe_bin = os.path.join(real_path, "ffmpeg\\bin\\ffprobe.exe")
else:
    raise RuntimeError("无法再该平台上运行")
sys.path.append(real_path)

MUSIC_PATH = "\\opt\\music"
if not os.path.exists(MUSIC_PATH):
    os.makedirs(MUSIC_PATH, exist_ok=True)

GLOBAL_MSG = ""


def exe_cmd(cmd, timeout=10, logger=None):
    # global GLOBAL_MSG
    try:
        s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = s.communicate(timeout=timeout)
        code = s.returncode
        print("code:{}".format(code))
        print("stdout:{}".format(stdout))
        print("stderr:{}".format(stderr))

        if code != 0:
            # GLOBAL_MSG = stderr.decode('utf-8', errors='ignore')
            # GLOBAL_MSG = code
            return code, "{}".format(stderr.decode('utf-8', errors='ignore'))
            # return code, code
        else:
            # GLOBAL_MSG = stdout.decode('utf-8', errors='ignore')
            # GLOBAL_MSG = code
            return code, "{}".format(stdout.decode('utf-8', errors='ignore'))
            # return code, code
    except Exception as e:
        print(e)
        # GLOBAL_MSG = str(e)
        return CODE_ERROR, e
        # GLOBAL_MSG = code
        # return code, code


class MainRecorderd(object):
    def __init__(self, ui, name, duration, size=None):
        self._duration = None
        self._name = None
        self._size = None
        self.ui = ui

        self._name = name
        self._duration = duration
        self._size = size
        self._v_type = '.mp4'
        self._music_file_path = None

        self.ui.title('录屏软件         --feiying 2025.9.8')
        self.ui.geometry('400x150+1080+100')  # 宽x高+偏移量
        self.setupui()

    def setupui(self):

        size_label = tk.Label(self.ui, text=u'区域（宽:高:X:Y）：')
        size_label.grid(row=1, column=1)

        size_var = tk.StringVar()
        if self._size is None:
            self._size = '790:582:250:125'  # 宽度:高度:起始X坐标:起始Y坐标
        size_var.set(self._size)
        self.size_input = tk.Entry(self.ui, textvariable=size_var, width=40)
        self.size_input.grid(row=1, column=2, padx=10, pady=5)

        name_label = tk.Label(self.ui, text=u'歌名：')
        name_label.grid(row=2, column=1)

        name_var = tk.StringVar()
        name_var.set(self._name)
        self.name_input = tk.Entry(self.ui, textvariable=name_var, width=40)
        self.name_input.grid(row=2, column=2, padx=10, pady=5)

        time_label = tk.Label(self.ui, text=u'时间：')
        time_label.grid(row=3, column=1)

        time_var = tk.StringVar()
        time_var.set(self._duration)
        self.time_input = tk.Entry(self.ui, textvariable=time_var, width=40)
        self.time_input.grid(row=3, column=2, padx=10, pady=5)
        self.time_input.config(text=self._duration)

        btn_run = tk.Button(self.ui, text=u'录制', width=10, command=self.do)
        btn_run.grid(row=4, column=1)

        self.msg_label = tk.Label(self.ui, text=u'')
        self.msg_label.grid(row=4, column=2)

    def str_time_to_second(self):
        temp_dt = datetime.strptime(self._duration, "00:%M:%S")
        return temp_dt.hour * 3600 + temp_dt.minute * 60 + temp_dt.second

    def do(self):
        # self.msg_label.config(text='')
        try:
            self._name = self.name_input.get()
            self._duration = self.time_input.get()
            self._size = self.size_input.get()
            if isinstance(self._duration, str):
                # self._duration = datetime.strftime("00:%M:%S")
                self._duration = self.str_time_to_second()
            show_str = "开始录制...{}".format(self._name)
            self.msg_label.config(text=show_str)
            self.msg_label.update()
            print("init: ", self._name, self._duration)

            self._music_file_path = os.path.join(MUSIC_PATH, self._name + self._v_type)

            if self._size is None or self._size == "":
                self._size = '790:582:250:125'  # 宽度:高度:起始X坐标:起始Y坐标
            if os.path.exists(self._music_file_path):
                os.remove(self._music_file_path)
            cmd = '{ffmpeg} -f gdigrab -i desktop -f dshow -i audio="virtual-audio-capturer" ' \
                  '-c:v libx264 -c:a aac -t {time} -vf "crop={size}" {name}'.format(
                ffmpeg=ffmpeg_bin, name=self._music_file_path, time=self._duration, size=self._size
            )
            print(cmd)
            # code, msg = exe_cmd(cmd, timeout=self._duration + 2)
            # code, msg = subprocess.getstatusoutput(cmd)
            # a = Process(target=exe_cmd, args=(cmd, self._duration+2))
            a = Thread(target=exe_cmd, args=(cmd, self._duration + 1))
            # a.daemon = True
            # print(a)
            a.start()
            # print(a)
            a.join()
            # print(a)
            # os.system(cmd)
            # code, msg = "", ""
            # print("code:", code)
            # print("msg: ", msg)
            # global GLOBAL_MSG
            show_str = "录制结束\n"
        except Exception as e:
            show_str = str(e)
        self.msg_label.config(text=show_str)
        # GLOBAL_MSG = ''


if __name__ == '__main__':
    freeze_support()
    name = "mp3歌名"
    duration = "00:03:06"
    size = '790:582:250:125'
    ui = Tk()
    rd = MainRecorderd(ui, name, duration)
    # rd.do()
    ui.mainloop()
